package com.example.docker_work.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.docker_work.dao.UserDao;
import com.example.docker_work.model.User;
import com.example.docker_work.respose.ReposeMessages;
import com.example.docker_work.service.UpdateExcelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UpdateExcelServiceImpl extends ServiceImpl<UserDao, User> implements UpdateExcelService {


    private static Pattern pattern = Pattern.compile("^[0-9]*\\.?[0-9]+$");

    @Autowired
    private UserDao userDao;

    @Override
    public ReposeMessages updated(MultipartFile multipartFile) {
        log.info("解析文件开始!");
        ReposeMessages reposeMessages = new ReposeMessages();
        InputStream inputStream = null;
        XSSFWorkbook workbook = null;
        try {
            String name = multipartFile.getOriginalFilename();
            String substring = name.substring(name.lastIndexOf("."));
            if (substring.equals(".xlsx") || substring.equals(".xls")) {
                if (multipartFile.getSize() > 1024*1024*5) {
                    return new ReposeMessages("600007", "文件大小不得大于5M");
                }
                inputStream = multipartFile.getInputStream();
                workbook = (XSSFWorkbook)WorkbookFactory.create(inputStream);
                //获取Excel的第一页数据
                Sheet sheet = workbook.getSheetAt(0);
                //获取总行数
                int rows = sheet.getLastRowNum();
                if (rows > 1000) {
                    return new ReposeMessages("600000", "行数过多");
                }
                List<User> userList = new ArrayList<>();
                for (int i = 1; i < rows+1; i++) {
                    log.info("================第"+i+"行数据");
                    //当前行
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }
                    int columns = row.getLastCellNum();
                    if (columns > 4) {
                        return new ReposeMessages("600006", "第"+(i+1)+"行列数过多");
                    }
                    User user = new User();
                    for (int j = 0; j < columns; j++) {
                        //获取单元格中的数据
                        Cell cell = row.getCell(j);
                        cell.setCellType(CellType.STRING);
                        String contents = cell.getStringCellValue();
                        //姓名
                        if (j == 0) {
                            user.setUsername(contents);
                        }
                        //年龄
                        if (j == 1) {
                            boolean numeric = isAge(contents);
                            //判断是否为正确的年龄
                            if (!numeric) {
                                return new ReposeMessages("600003", "第"+(i+1)+"行请输正确的年龄");
                            }
                            user.setAge(Integer.parseInt(contents));
                        }
                        //身高
                        if (j == 2) {
                            boolean numeric = isHeight(contents);
                            //判断是否为正确的身高
                            if (!numeric) {
                                return new ReposeMessages("600004", "第"+(i+1)+"行请输正确的身高");
                            }
                            user.setHeight(new BigDecimal(contents));
                        }
                        //爱好
                        if (j==3) {
                            if (contents.length() > 200) {
                                return new ReposeMessages("600005", "第"+(i+1)+"行爱好长度过长");
                            }
                            user.setHobby(contents);
                        }
                    }
                    userList.add(user);
                }
                insertUser(userList);
            } else {
                return new ReposeMessages("600007","只能上传excel文件");
            }
        } catch (IOException  | InvalidFormatException e) {
            reposeMessages = new ReposeMessages("600002", "解析文件失败！");
        } finally {
            if (inputStream !=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.info("关闭输入流");
                }
            }
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return reposeMessages;
    }

    private boolean isAge(String str){
        boolean matches = pattern.matcher(str).matches();
        if (matches) {
            int i = Integer.parseInt(str);
            if (i>100 || i < 0) {
                return false;
            }
        }
        return matches;
    }

    private boolean isHeight(String str){
        boolean matches = pattern.matcher(str).matches();
        if (matches) {
            int i = Integer.parseInt(str);
            if (i < 0 || str.length() > 3) {
                return false;
            }
        }
        return matches;
    }

    private void insertUser(List<User> userList){
        if (userList.size() > 0) {
            for (User user : userList) {
                userDao.insert(user);
            }
        }
    }
}
